# -*- coding: utf-8 -*-

from common.models.keymap import Keymap
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from dingtalk import SecretClient, AppKeyClient
from flask import Blueprint, request, make_response, redirect
from common.models.user import User
import json, requests
import pandas as pd
import datacompy
import time
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
from common.libs.mydingtalk import DingTalkCrypto
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, spaceId,loaclurl,bpmid,res_aes_key,res_token

index_page = Blueprint("index_page", __name__)

client = SecretClient(AppKey, AppSecret)


@index_page.route("/")
def login():
    return ops_render("/member/login.html")


@index_page.route("/index")
def index():
    return ops_render("index.html")


@index_page.route('/getkeymapname', methods=['GET', 'POST'])
def getkeymapname():
    keyname = request.json.get('keyname')
    keyname = Keymap.query.filter(Keymap.key.in_(keyname)).all()
    rts = []
    for item in keyname:
        rts.append(item.name)

    return json.dumps(rts, ensure_ascii=False)


@index_page.route('/getkeymapkey', methods=['GET', 'POST'])
def getkeymapkey():
    keyname = request.json.get('keyname')
    keyname = Keymap.query.filter(Keymap.name.in_(keyname)).all()
    rts = []
    for item in keyname:
        rts.append(item.key)

    return json.dumps(rts, ensure_ascii=False)


def result_success(encode_aes_key, token, corp_id):
    """封装success返回值"""
    dtc = DingTalkCrypto(encode_aes_key, corp_id)
    encrypt = dtc.encrypt('success')
    timestamp = str(int(round(time.time())))
    nonce = dtc.generateRandomKey(8)
    # 生成签名
    signature = dtc.generateSignature(nonce, timestamp, token, encrypt)
    # 构造返回数据
    new_data = {
        'msg_signature': signature,
        'timeStamp': timestamp,
        'nonce': nonce,
        'encrypt': encrypt
    }
    return new_data


def encrypt_result(encode_aes_key, din_corpid, encrypt):
    """解密钉钉回调的返回值"""
    dtc = DingTalkCrypto(encode_aes_key, din_corpid)
    return dtc.decrypt(encrypt)


def getDecryptMsg(msg_signature, timeStamp, nonce, content, encode_aes_key, din_corpid, token):
    dtc = DingTalkCrypto(encode_aes_key, din_corpid)
    sign = dtc.generateSignature(nonce, timeStamp, token, content)
    if msg_signature != sign:
        raise ValueError('signature check error')


# @index_page.route("/dingtalkfileupload", methods=['GET', 'POST'])
# def dingtalkfileupload():
#     code = request.form.get("code")
#     userid = request.form.get("userid")
#     file = request.files.getlist('files')
#
#     print(file)
#     print(code)
#
#     # data = request.values.to_dict()
#     # code = data["code"]
#     # userid = data["userid"]
#     # print(code)
#     # print(userid)
#     # file = request.files['file']
#     # print(file)
#     time = str(getCurrentTime())
#     sn = time.replace("-", "").replace(" ", "").replace(":", "")
#     name = sn+file.filename
#     size = file.content_length
#
#     token_params = {
#         'appkey': AppKey,
#         'appsecret': AppSecret,
#     }
#     dd_token = 'https://oapi.dingtalk.com/gettoken'
#     token_response = requests.get(dd_token, params=token_params)  # 向API发起GET请求
#     tokenData = token_response.json()
#     access_token = tokenData['access_token']
#
#     url = 'https://oapi.dingtalk.com/topapi/processinstance/cspace/info?access_token=' + access_token
#
#     userid_params = {
#         "user_id": userid,
#     }
#     userid_response = requests.post(url, params=userid_params)  # 向API发起GET请求
#     resdata = userid_response.json()
#
#     media_id = client.cspace.file_upload_single(agent_id=AgentId, file_size=size, media_file=file)
#
#     result = resdata['result']
#     space_id = result['space_id']
#     print(media_id)
#
#
#     fileadd = client.cspace.add(code=code, space_id=space_id, folder_id=0, media_id=media_id, agent_id=AgentId,
#                                 name=name)
#
#     file_id = fileadd["id"]
#     filename = fileadd["name"]
#     filesize = fileadd["size"]
#     filetype = fileadd["extension"]
#
#
#
#     return json.dumps(
#         {"spaceId": space_id, "fileId": file_id, "fileName": filename, "fileSize": filesize, "fileType": filetype},
#         ensure_ascii=False)


@index_page.route("/dingtalkfileupload", methods=['GET', 'POST'])
def dingtalkfileupload():
    code = str(request.form.get("code"))
    codelist = code.split(",")
    userid = request.form.get("userid")

    f = request.files.getlist('files')

    time = str(getCurrentTime())
    sn = time.replace("-", "").replace(" ", "").replace(":", "")

    token_params = {
        'appkey': AppKey,
        'appsecret': AppSecret,
    }
    dd_token = 'https://oapi.dingtalk.com/gettoken'
    token_response = requests.get(dd_token, params=token_params)  # 向API发起GET请求
    tokenData = token_response.json()
    access_token = tokenData['access_token']

    url = 'https://oapi.dingtalk.com/topapi/processinstance/cspace/info?access_token=' + access_token

    userid_params = {
        "user_id": userid,
    }
    userid_response = requests.post(url, params=userid_params)  # 向API发起GET请求
    resdata = userid_response.json()
    result = resdata['result']
    space_id = result['space_id']
    print(result)

    rts = []

    for item in f:
        name = sn + item.filename
        size = item.content_length
        media_id = client.cspace.file_upload_single(agent_id=AgentId, file_size=size, media_file=item)

        try:
            fileadd = client.cspace.add(code=codelist[f.index(item)], space_id=space_id, folder_id=0,
                                        media_id=media_id,
                                        agent_id=AgentId,
                                        name=name)
        except:
            return ops_renderJSON(msg="上传失败")
        file_id = fileadd["id"]
        filename = fileadd["name"]
        filesize = fileadd["size"]
        filetype = fileadd["extension"]

        temp = dict(spaceId=space_id, fileId=file_id, fileName=filename, fileSize=filesize, fileType=filetype)
        rts.append(temp)
        print("上传成功")
    return ops_renderJSON(msg="附件上传成功", data={"fileinfo": rts})




@index_page.route('/submitimage', methods=['GET', 'POST'])
def submitImage():
    file = request.files['file']
    # 上传到七牛后保存的文件名
    key="OMH_KB"+str(int(time.time()))+file.filename
    # print file.filename
    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'guanzhuoran'
    #http://+外链域名
    domian_name = 'http://upload.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # ret, info = _form_put(token, key, file.read(),params=None,
    #          mime_type='application/octet-stream', crc=None)

    ret, info=put_data(token, key, file.read(),params=None,
              mime_type='application/octet-stream')

    return '{"location":"'+domian_name+"/"+key+'"}'





@index_page.route('/qiniufileupload', methods=['GET', 'POST'])
def qiniufileupload():
    file = request.files['file']
    # 上传到七牛后保存的文件名
    name = file.filename

    key = str(int(time.time())) + name
    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'guanzhuoran'
    # http://+外链域名
    domian_name = 'http://upload.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # ret, info = _form_put(token, key, file.read(),params=None,
    #          mime_type='application/octet-stream', crc=None)

    ret, info = put_data(token, key, file.read(), params=None,
                         mime_type='application/octet-stream')
    url = domian_name + key

    return json.dumps("aa", ensure_ascii=False)  # rts


@index_page.route('/dingtalkrecall', methods=['GET', 'POST'])
def dingtalkrecall():
    aes_key = res_aes_key
    token = res_token
    corp_id = AppKey

    # 注册函数
    # reg = result_success(aes_key, token, corp_id)

    result_success(aes_key, token, corp_id)
    json_data = request.json.get("encrypt")
    request_data = request.values
    getDecryptMsg(request_data['signature'], request_data['timestamp'], request_data['nonce'],
                  json_data, aes_key, corp_id, token)
    type_info = encrypt_result(aes_key, corp_id, json_data)
    type_name = json.loads(type_info)
    # print(type_name.get("processInstanceId"))
    # print(type_name)
   # # 入职
   #  if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
   #          "result") == "agree" and type_name.get("processCode") == bpmid["入职流程"]:
   #      params = {
   #          "processInstanceId": type_name.get("processInstanceId"),
   #      }
   #      url = loaclurl+'member/adduser'
   #      response = requests.post(url, params=params)  # 向API发起GET请求
   # 调岗
    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "agree" and type_name.get("processCode") == bpmid["调岗流程"]:

        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        url = loaclurl+'member/changeuser'
        response = requests.post(url, params=params)  # 向API发起GET请求
    # # 辞退
    # if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
    #         "result") == "agree" and type_name.get("processCode") == bpmid["辞退流程"]:
    #     params = {
    #         "processInstanceId": type_name.get("processInstanceId"),
    #     }
    #     url = loaclurl + 'member/dismissuser'
    #     response = requests.post(url, params=params)  # 向API发起GET请求
    # 转正
    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "agree" and type_name.get("processCode") == bpmid["转正流程"]:
        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        url = loaclurl + 'member/employuser'
        response = requests.post(url, params=params)  # 向API发起GET请求
    # 辞职
    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "agree" and type_name.get("processCode") == bpmid["辞职流程"]:
        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        url = loaclurl + 'member/resignuser'
        response = requests.post(url, params=params)  # 向API发起GET请求

    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "agree" and type_name.get("processCode") == bpmid["浮动工资"]:
        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        url = loaclurl + 'award/bpmagree'
        response = requests.post(url, params=params)  # 向API发起GET请求

    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "refuse" and type_name.get("processCode") == bpmid["浮动工资"]:
        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        url = loaclurl + 'award/bpmrefuse'
        response = requests.post(url, params=params)  # 向API发起GET请求

    if type_name.get('EventType') == "bpms_instance_change" and type_name.get('type') == "finish" and type_name.get(
            "result") == "agree" and type_name.get("processCode") == bpmid["出差流程"]:
        params = {
            "processInstanceId": type_name.get("processInstanceId"),
        }
        print(params)
        # url = loaclurl + 'connector/test'
        # response = requests.post(url, params=params)  # 向API发起GET请求

    # if type_name.get('EventType') == 'attendance_check_record' :
    #     # print(type_name.get('DataList')[0]['userId'])
    #
    #     params = {
    #         "userid": type_name.get('DataList')[0]['userId'],
    #         "time":type_name.get('DataList')[0]['checkTime'],
    #         "type":type_name.get('DataList')[0]['locationResult'],
    #     }
    #     url = loaclurl + 'check/add'
    #     response = requests.post(url, params=params)  # 向API发起GET请求




    return json.dumps("reg", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)

